#include"include.h"
#define FILEROAD "/mnt/config/table.json"

void deserialization(struct device * p,struct data *Data)
{
    struct device *temp = p;
    struct stat st;
    stat(FILEROAD, &st);
    if (!st.st_size)
    {
        printf("等待上位机下发点表\n");
        sleep(3);
        char *args[] = {"./stm32_service",NULL};
        execv(args[0], args);
    }
    // 读取点表
    char *buf = (char *)malloc(st.st_size);
    if (buf == NULL)
    {
        printf("开辟空间失败\n");
        return;
    }
    FILE *fp = fopen(FILEROAD, "r+");
    if (fp == NULL)
    {
        perror("err");
        return;
    }
    printf("文件大小:%ld\n", st.st_size);
    fread(buf, 1, st.st_size, fp);
    // 反序列化
    cJSON *root;
    root = cJSON_Parse(buf);
    // 获取设备节点
    cJSON *stm32 = cJSON_GetObjectItem(root, "stm32");
    cJSON *stm32Data = cJSON_GetObjectItem(stm32, "data");
    // 设备数量存放
    temp->stm32Num = cJSON_GetArraySize(stm32Data);
    printf("stm32设备数量:%d\n", temp->stm32Num);
    // 设备数据存放
    struct data *dataptr = (struct data *)(temp + 1);
    for (int i = 0; i < temp->stm32Num; i++)
    {
        cJSON *item = cJSON_GetArrayItem(stm32Data, i);
        cJSON *key = cJSON_GetObjectItem(item, "key");
        Data[i].key = key->valueint;
        cJSON *name = cJSON_GetObjectItem(item, "name"); 
        strcpy(Data[i].name, name->valuestring);
        cJSON *type = cJSON_GetObjectItem(item, "type");
        Data[i].type = type->valueint;
        printf("Data[%d] key:%ld name:%s type:%d\n",i, Data[i].key,Data[i].name,Data[i].type );
        dataptr++;
    }
    printf("设备绑定完成\n");
    fclose(fp);
    cJSON_Delete(root);
    free(buf);
    buf = NULL;
}